/**


g++ -O0 -std=c++11 -lpthread stuck_process_cpu_on_off_line.cpp -o spcofl
./spcofl
*/

#include <errno.h>
#include <iostream>
#include <pthread.h>
#include <signal.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <string>
#include <sys/stat.h>
#include <sys/time.h>
#include <sys/types.h>
#include <unistd.h>

#ifndef CPU_CORE_COUNT
#define CPU_CORE_COUNT 64
#endif

using namespace std;

// common lib
bool is_dir(const std::string &path) {
  struct stat statbuf;
  if (stat(path.c_str(), &statbuf) == 0) {
    if (0 != S_ISDIR(statbuf.st_mode)) {
      return true;
    }
  }
  return false;
}

bool write_file(const std::string &file_path, int num) {
  // std::cout << file_path << " op:" << num << std::endl;
  FILE *fp = fopen(file_path.c_str(), "w");
  if (fp == NULL) {
    return false;
  }

  // std::cout << file_path << " op:" << num << std::endl;
  std::string write_data = to_string(num);
  fputs(write_data.c_str(), fp);
  fclose(fp);
  return true;
}

std::string read_file(const std::string &file_path) {
  FILE *fp = fopen(file_path.c_str(), "r");
  if (NULL == fp) {
    return "read error...\n";
  }
  char buff[512];
  memset(buff, 0, 512);
  fread(buff, 512, 1, fp);
  fclose(fp);
  return std::string(buff);
}

bool set_cpuOnline(int cpuId, int online) {
  std::string cpuPath = std::string("/sys/devices/system/cpu/cpu") +
                        std::to_string(cpuId) + std::string("/online");
  return write_file(cpuPath, online);
}

// thread
// param: ms interval
void *thread_func(void *param) {
  int i;
  while (true) {
  }

  pthread_exit(NULL);
}

void test_thread() {
  const int k_thread_num = CPU_CORE_COUNT * 10;
  pthread_t pthreads[k_thread_num];

  for (int i = 0; i < k_thread_num; i++) {
    if (pthread_create(&pthreads[i], NULL, thread_func, NULL) != 0) {
      cout << "create thread fail" << endl;
    } else {
      cout << "create thread success,tid is " << pthreads[i] << endl;
    }
  }
}

void *thread_cpu_online_ctl(void *param) {
  int online, cpu;
  bool b;
  while (true) {
    online = rand() % 2;
    cpu = rand() % CPU_CORE_COUNT;
    b = set_cpuOnline(cpu, online);
    std::cout << cpu << " -> " << online << "result:" << b << std::endl;
    std::cout << read_file("/sys/devices/system/cpu/online") << std::endl;
  }

  pthread_exit(NULL);
}

void cpu_ctl_thread() {
  const int k_thread_num = CPU_CORE_COUNT;
  pthread_t pthreads[k_thread_num];

  for (int i = 0; i < k_thread_num; i++) {
    if (pthread_create(&pthreads[i], NULL, thread_cpu_online_ctl, NULL) != 0) {
      cout << "create thread fail" << endl;
    } else {
      cout << "create thread success,tid is " << pthreads[i] << endl;
    }
  }
}

int main(int argc, char *argv[]) {

  int period = 100000;
  int quota = CPU_CORE_COUNT * 0.8 * 100000;
  cout << "period is " << period << endl;
  cout << "quota is " << quota << endl;
  srand(time(nullptr));

  test_thread();
  cpu_ctl_thread();

  while (true) {
    sleep(10000);
  }

  return 0;
}
